package com.lingyun.ucm.common.zk;

import org.I0Itec.zkclient.ZkClient;

import com.lingyun.ucm.common.bootstrap.Bootstrap;
import com.lingyun.ucm.common.exception.UtilException;
import com.lingyun.ucm.common.util.Constant;
/**
 * 
 * @author Terrence2013
 * 2018年1月24日 上午9:49:34
 * ZKClient工具类
 */
public class ZkClientUtil {
    private ZkClientUtil() {}
    /**
     * 获取节点路径
     * @param systemName
     * @param moduleName
     * @param key
     * @return
     */
    public static String getNodePath(String systemName, String moduleName, String key) {
        StringBuilder builder = new StringBuilder();
        builder.append(Constant.ZK_ROOT_PATH)
                .append("/").append(systemName)
                .append("/").append(moduleName)
                .append("/").append(key);
        return builder.toString();
    }

    /**
     * 验证路径
     * @param path
     * @throws UtilException
     */
    public static void checkPath(String path) throws UtilException {
        if (path.split("/").length != Constant.CONFIG_TOTAL_LENGTH) {
            throw new UtilException("配置信息不合法!");
        }
    }

    /**
     * 拼接获取key
     * @param systemName
     * @param moduleName
     * @param configKey
     * @return
     */
    public static String appendKey(String systemName, String moduleName, String configKey) {
        StringBuilder builder = new StringBuilder();
        builder.append(systemName).append(".")
               .append(moduleName).append(".")
               .append(configKey);
        return builder.toString();
    }

    /**
     * 获取zk连接对象
     * @return
     */
    public static ZkClient createZkClient() {
        return new ZkClient(Bootstrap.inst().getCache().getZookeeper(),10000,10000);
    }
    
    public static void closeZkClient(ZkClient zkClient){
    	if(null!=zkClient){
    		zkClient.close();
    	}
    }
    
    /**
     * 通过path返回配置key,格式为:"xxx.xxx.xxx"
     * @param path
     * @return
     */
    public static String getClientKeyFromPath(String path) {
        path = path.replace(Constant.ZK_ROOT_PATH + "/", "");
        return path.replaceAll("\\/", ".");
    }

    /**
     * 通过key返回path,格式为:"xxx.xxx.xxx"
     * @param configKey
     * @return
     */
    public static String getPathFromClientKey(String configKey) {
        return Constant.ZK_ROOT_PATH + "/" + configKey.replaceAll("\\.", "/");
    }
}
